<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="5" style="margin-bottom: 10px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <div>
            <div style="text-align: center">
              <el-upload
                  class="avatar-uploader"
                  :action="updateAvatarApi"
                  :show-file-list="false"
                  :on-success="cropUploadSuccess"
                  :on-error="uploadError"
              >
                <el-image :src="baseApi+user.avatarName" class="avatar">
                  <div slot="error" class="image-slot">
                    <el-image :src="Avatar" class="avatar"></el-image>
                  </div>
                </el-image>
              </el-upload>
            </div>
            <ul class="user-info">
              <li>
                <div style="height: 100%">
                  登录账号
                  <div class="user-right">{{ user.username }}</div>
                </div>
              </li>
              <li>
                用户昵称
                <div class="user-right">{{ user.nickName }}</div>
              </li>
              <li>
                手机号码
                <div class="user-right">{{ user.phone }}</div>
              </li>
              <li>
                安全设置
                <div class="user-right">
                  <a @click="updatePassword">修改密码</a>
                </div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="16" :lg="18" :xl="19">
        <!--    用户资料    -->
        <el-card class="box-card">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="用户资料" name="first">
              <el-form ref="form" :model="formData" :rules="rules" style="margin-top: 10px;" label-width="65px">
                <el-form-item label="昵称" prop="nickName">
                  <el-input v-model="formData.nickName" style="width: 35%"/>
                  <span style="color: #C0C0C0;margin-left: 10px;">用户昵称不作为登录使用</span>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="formData.phone" style="width: 35%;"/>
                  <span style="color: #C0C0C0;margin-left: 10px;">手机号码不能重复</span>
                </el-form-item>
                <!--                <el-form-item label="性别">-->
                <!--                  <el-radio-group v-model="formData.gender" style="width: 178px">-->
                <!--                    <el-radio label="男">男</el-radio>-->
                <!--                    <el-radio label="女">女</el-radio>-->
                <!--                  </el-radio-group>-->
                <!--                </el-form-item>-->
                <el-form-item label="">
                  <el-button :loading="saveLoading" type="primary" @click="doSubmit">保存配置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <!--    操作日志    -->
            <el-tab-pane label="操作日志" name="second">

              <el-table :data="dataList" style="width: 100%;">
                <el-table-column prop="description" label="行为"/>
                <el-table-column prop="requestIp" label="IP"/>
                <el-table-column :show-overflow-tooltip="true" prop="address" label="IP来源"/>
                <el-table-column prop="browser" label="浏览器"/>
                <el-table-column prop="time" label="请求耗时" align="center">
                  <template #default="scope">
                    <el-tag v-if="scope.row.time <= 300">{{ scope.row.time }}ms</el-tag>
                    <el-tag v-else-if="scope.row.time <= 1000" type="warning">{{ scope.row.time }}ms</el-tag>
                    <el-tag v-else type="danger">{{ scope.row.time }}ms</el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                    align="right"
                    width="200px"
                    label="时间"
                >
                  <template #default="scope">
                    <span>{{ scope.row.createTime }}</span>
                  </template>
                </el-table-column>
              </el-table>
              <pagination v-model:page="queryParam.page" v-model:limit="queryParam.size" :total="total"
                          @change="initList()"/>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
    <comm-edit-dialog v-model:dialog-show="editDialogShow" @save="doSure" :save-loading="saveLoading" title="修改密码">
      <template #content>
        <el-form ref="form" :model="formData" :rules="modifyRules" label-width="88px">
          <el-form-item label="旧密码" prop="oldPass">
            <el-input v-model="formData.oldPass" type="password" auto-complete="on" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="新密码" prop="newPass">
            <el-input v-model="formData.newPass" type="password" auto-complete="on" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPass">
            <el-input v-model="formData.confirmPass" type="password" auto-complete="on" style="width: 370px;"/>
          </el-form-item>
        </el-form>
      </template>
    </comm-edit-dialog>
  </div>
</template>


<script setup>
import {computed, getCurrentInstance, onBeforeUnmount, onMounted, ref, reactive, toRefs} from "vue";
import mixins from "@/mixins/mixins";
import store from "@/store";
import {isvalidPhone} from '@/utils/validate'
import Pagination from "@/components/Pagination/index.vue";
import Avatar from '@/assets/images/avatar.png'
import CommEditDialog from "@/components/Comm/CommEditDialog.vue";
import {ElMessage} from 'element-plus'
import { encrypt } from '@/utils/rsaEncrypt'
import {post,put} from "@/utils/request";
import {validatePass} from "@/utils/util";


const avatar = computed(() => store.state.avatar);
const baseApi = import.meta.env.VITE_BASE_IMG_URL
const updateAvatarApi = ref(import.meta.env.VITE_BASE_API+'/users/avatar')
const {initList, data, total, dataList, toAdd, toSave} = mixins()
const {baseUrl, loading, queryParam, formData, saveLoading, editDialogShow} = toRefs(data)
baseUrl.value = '/logs/user'
//
const validPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入电话号码'))
  } else if (!isvalidPhone(value)) {
    callback(new Error('请输入正确的11位手机号码'))
  } else {
    callback()
  }
}

const confirmPass = (rule, value, callback) => {
  if (value) {
    if (formData.value.newPass !== value) {
      callback(new Error('两次输入的密码不一致'))
    } else {
      callback()
    }
  } else {
    callback(new Error('请再次输入密码'))
  }
}

const pageData = reactive(
    {
      form: {aa: 1},
      rules: {
        nickName: [
          {required: true, message: '请输入用户昵称', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ],
        phone: [
          {required: true, trigger: 'blur', validator: validPhone}
        ]
      },
      modifyRules:{
        // oldPass: [
        //   {required: true,validator: validatePass, trigger: 'blur'}
        // ],
        // newPass: [
        //   {required: true, trigger: 'blur',validator: validatePass},
        // ],
        // confirmPass: [
        //   {required: true, validator: confirmPass, trigger: 'blur'}
        // ]
      }
    }
)

const user = ref({})
const {form, rules,modifyRules} = toRefs(pageData)
const activeName = ref('first')
const {proxy} = getCurrentInstance();
const passRef = ref()
const showUpPass = ref(false)

function handleClick(tab, event) {
  if (tab.paneName === 'second') {
    initList()
  }
}

function doSubmit() {
  saveLoading.value = true;
  const form = proxy.$refs['form']
  form.validate((valid) => {
    if (valid) {
      saveLoading.value = true
      put('/users/center',formData.value).then(() => {
        setTimeout(function () {
          initUserInfo()
        }, 500)
        ElMessage({
          message: '修改成功',
          type: 'success'
        });
        saveLoading.value = false
      }).catch(() => {
        saveLoading.value = false
        ElMessage({
          message: '修改失败',
          type: 'error'
        });
      })
    }
  })
}

function cropUploadSuccess(res, file) {
  initUserInfo()
}

function uploadError(err) {
  let myError = err.toString();//转字符串
  myError = myError.replace("Error: ", "") // 去掉前面的" Error: "
  myError = JSON.parse(myError);//转对象
  ElMessage({message: myError.message})
}

function initUserInfo() {
  store.dispatch('getUserInfo').then((res) => {
    user.value = res
    formData.value = {id: res.id, nickName: res.nickName, phone: res.phone}
    console.log(res)
  })
}

function updatePassword() {
  toAdd()
}

function doSure() {
  baseUrl.value='/users/updatePass'

  toSave('form', () => {
    baseUrl.value = 'api/logs/user'
    ElMessage({message: "修改成功,请重新登录"})
    setTimeout(() => {
      store.dispatch('logout')
    }, 1500)
  },()=>{
     var methodData=Object.assign({},formData.value)
    methodData.oldPass=encrypt(methodData.oldPass)
    methodData.newPass=encrypt(methodData.newPass)
    methodData.confirmPass=encrypt(methodData.confirmPass)
    return methodData;

  })
}

//
onMounted(() => {
  initUserInfo()
})

</script>

<style rel="stylesheet/scss" lang="scss">
.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
}

.user-info {
  padding-left: 0;
  list-style: none;

  li {
    border-bottom: 1px solid #F0F3F4;
    padding: 11px 0;
    font-size: 13px;
  }

  .user-right {
    float: right;

    a {
      color: #317EF3;
    }
  }
}
</style>
